package com.hd.manager.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hd.appcommon.utils.ICallBack;
import com.hd.manager.webSocket.DeviceEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

import static com.hd.manager.webSocket.EndpointManager.getEnpoint;

/**
 * @projectName:    entrance_guard 
 * @package:        com.hd.manager.util
 * @className:      JieShiActivateRequestUtil
 * @author:     otto
 * @description:  
 * @date:    2023/7/24 15:07
 * @version:    1.0
 */ 

@Slf4j
@Component
public class JieShiActivateRequestCallBackUtil {
    /**
     * @Param type 请求类型，发送请求时会打印日志
     * @param requestMap 用于获取session
     */
    // 线程安全的HashMap long型 的pkgId  String型的message
    private static final ConcurrentHashMap<Long,String> productMap = new ConcurrentHashMap<>();

    @Autowired
    private CallBackUtil callBackUtil;

    public void setMessage(Long requestId,JSONObject jsonObject){
        ICallBack callBack = callBackUtil.getCallBackMap().get(requestId);
        if(callBack!=null){
            callBack.service(jsonObject);
            callBackUtil.getCallBackMap().remove(requestId);
        }
    }


    /**
     * 将消费需求挂上map
     * @param requestId
     */
    public void setVoidKey(Long requestId){
        productMap.put(requestId,"");
    }

    private JSONObject thisJsonObject;

    final Object object = new Object();


    @Autowired
    private DeviceEndpoint deviceEndpoint;
    public JSONObject activateRequest(HashMap<String,Object> requestMap) throws InterruptedException {
        // 获取session
        /*先获取用户列表*/
        String requestType = (String) requestMap.get("request_type");

        log.info("发起"+requestType+"请求");
        String deviceId = (String) requestMap.get("device_id");
        DeviceEndpoint deviceEndpoint = getEnpoint(deviceId);

        String message = JSON.toJSONString(requestMap);
        System.out.println("message \n "+message);
//        try{
            deviceEndpoint.sendMessage(message);
            Long requestId =Long.valueOf(requestMap.get("request_id").toString());
            callBackUtil.sendForBlock(requestId, new ICallBack() {
                @Override
                public void service(JSONObject jsonObject) {
                    thisJsonObject = jsonObject;
                    synchronized (object){
                        object.notifyAll();
                    }
                }
            });
            synchronized (object){
                object.wait(30000);
                callBackUtil.getCallBackMap().remove(requestId);
            }
            return thisJsonObject;
//        }catch (Exception e){
//            log.error(requestType+"请求失败！");
//            log.error(e.toString());
//            return null;
//        }
    }
}
